﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace net.veekee.common.data.csv
{
    public class CSVReaderFile : ACSVFile
    {
        private StreamReader sr = null;

        public override bool IsValid
        {
            get
            {
                return this.sr != null;
            }
        }

        public CSVReaderFile(String filename, char separator = ';')
            : base(filename, separator)
        {
            this.LoadFile(separator, Encoding.Default);
        }

        public CSVReaderFile(String filename, Encoding encode, char separator = ';')
            : base(filename, separator)
        {
            this.LoadFile(separator, encode);
        }

        private void LoadFile(char separator, Encoding encode)
        {
            try
            {
                if (!System.IO.File.Exists(this.fileName))
                    return;
                this.sr = new StreamReader(this.fileName, encode);
                this.SelectSheet(0);
            }
            catch (Exception e)
            {
                Log.GetInstance().Error(e.ToString());
            }
        }

        public override void LoadHeader()
        {
            try
            {
                String lheader = this.NextLine();
                if (lheader == null)
                    return;
                String[] aheader = lheader.Split(this.fieldSeparator);
                for (int i = 0; i < aheader.Length; i++)
                {
                    this.header.Add(i, aheader[i]);
                }
            }
            catch (Exception e)
            {
                Log.GetInstance().Error("CSV file '{0}' couldn't be loaded: {1}", this.FileName, e.ToString());
            }
        }

        private String NextLine()
        {
            if (! this.IsValid)
                return null;
            if (this.sr.EndOfStream)
                return null;
            this.LineNumber++;
            return this.sr.ReadLine();
        }

        public override AnEntry Next()
        {
            AnEntry obj = new AnEntry();
            String line = this.NextLine();
            if (line == null)
                return null;
            String[] csv = line.Split(this.fieldSeparator);
            try
            {
                obj.Line = this.LineNumber;
                obj.Load(this.header, new List<String>(csv));
            }
            catch (Exception e)
            {
                Log.GetInstance().Error("{0}@{1}: {2}", this.FileName, this.LineNumber, e.ToString());
            }
            return obj;
        }

        public override void Dispose()
        {
            if(this.sr != null)
                this.sr.Close();
            this.sr = null;
        }
    }
}
